--Recursive directory operation
function recursedirectory (path,callback,extensions,ignore)
    for file in lfs.dir(path) do
        if file ~= "." and file ~= ".." then
            local f = path..'/'..file
            local attr = lfs.attributes (f)
            assert (type(attr) == "table")
            if attr.mode == "directory" then
                recursedirectory (f,callback,extensions,ignore)
            else
                if extensions ~= nil then
                  if (checkextensions(file,extensions)) then
                    if ignore then
                      --ignored this file
                      print("ignored:",file)
                    else
                      callback(path,file)
                    end
                  end
                else --no special extensions requirements
                  callback(path,file)
                end  
            end
        end
    end
end

function checkextensions(file,extensions)
  for _, ext in ipairs (extensions) do
    if string.find(file,"%."..ext.."$") then
      return true
    end
  end  
  return false
end

recursedirectory(".",print,{"lua"})

function checkfornewfiles(path,callback,extensions,ignore)
  local o ={}
  o.path = path
  o.callback = callback
  o.extensions = extensions
  o.ignore = ignore
  o.lastcheck = time
  o.changed = {} --changed file list
  --function that is called recursively on files
  o.timechecker = function(self,path,file)
    local directoryactivity = false
    local attr = lfs.attributes (path.."/"..file)
    assert (type(attr) == "table")
    if (attr.modification  >self.lastcheck) then --has been accessed since last check
      directoryactivity = true
      table.insert(self.changed,{path,file}) --remember the path and file 
    end
    if (directoryactivity == false) and (#(self.changed)>0) then
      --the directory has cooled down, and we have a list of files to process
      for k,v in ipairs(self.changed) do
        callback(v[1],v[2])
      end
      self.changed = {} --clear table  
    end 
  end
  function wrap(self)
    return function(path,file)
      self:timechecker(path,file)
    end
  end
  o.check = function(self)
    recursedirectory(self.path,wrap(self),self.extensions,self.ignore)
    self.lastcheck = time
  end  
  return o
end

checker = checkfornewfiles(".",print,{"lua"})
checker:check()



